import { UserApi } from "../api/user.api"
import { HTTP_CODE } from "./request"

export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

/**登录方法 */
export function loginSystem() {
  wx.login({
    async success(res) {
      if (res.code) {
        console.log('用户登录 code:', res.code);
        let loginRes = await UserApi.login(res.code)
        if (loginRes.success) {
          console.log(loginRes.data.token);
          
          wx.setStorageSync("token", loginRes.data.token)
        } else if (loginRes.code === HTTP_CODE.unregistered) {
          wx.reLaunch({
            url: "/pages/signup/signup"
          })
        } else {
          wx.showLoading({
            title: loginRes.msg,
            mask: true,
          });
        }
      } else {
        console.log('登录失败！', res.errMsg);
      }
    }
  });
}